//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Security;
using System.Security.Permissions;
using System.Windows;
using System.Windows.Interop;

namespace OpenLS.Spreadsheet.UI
{
    static class ClipboardManager
    {
        internal static void Copy(Range selection)
        {
            PutInClipboard(selection, false);
            //\\  Clipboard.SetText(StringOf(selection)); //\\ add formats
        }
        public static void SetSelectionAddress (string address)
        {
            CurrentClipboard.SetSelectionAddress(address);
        }

        static ClipboardBase CurrentClipboard
        {
            get
            {
                if (_currentClipboard == null)
                {

                    if (!HasClipboardAccess)
                        _currentClipboard = new InternalClipboard();
                    else
                        _currentClipboard = new WindowsClipboard();
                }
                return _currentClipboard;
            }
        }
        static bool HasClipboardAccess
        {
            get
            {
                try
                {
                    UIPermission permission = new UIPermission(UIPermissionClipboard.AllClipboard);

                    permission.Demand();
                    return true;
                }
                catch (SecurityException)
                {
                    return false;
                    throw;
                }
            }
        }

        static ClipboardBase _currentClipboard;

        private static void PutInClipboard(Range selection, bool isCut)
        {
            LastWasCut = isCut;
            CurrentClipboard.SetRange(selection);
        }

        internal static void Cut(Range selection)
        {
            PutInClipboard(selection, true);
        }
        
        public static bool LastWasCut;

        internal static void Clear()
        {
            Clipboard.Clear();
        }

        internal static Range CopiedRange()
        {
            return CurrentClipboard.Copied();
        }
    }
}